package com.markerhub.mapper;

import com.markerhub.entity.Course;
import com.markerhub.entity.TeachingCalling;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;


@Mapper
public interface TeachingCallingMapper extends BaseMapper<TeachingCalling> {

    @Select("SELECT DISTINCT c.* FROM m_course c " +
            "INNER JOIN m_manager_class mc ON c.class_id = mc.id " +
            "WHERE c.teacher_id = #{teacherId} AND c.status = '1'")
    List<Course> getTeacherCourses(Integer teacherId);

    @Select("SELECT tc.*, mc.name as className, mt.teacher_name as teacherName " +
            "FROM m_teaching_calling tc " +
            "INNER JOIN m_manager_class mc ON tc.class_id = mc.id " +
            "INNER JOIN m_manager_teacher mt ON tc.creator = mt.id " +
            "WHERE tc.class_id = #{classId} AND tc.ended = '0'")
    List<TeachingCalling> getActiveCallingsByClassId(Integer classId);

    @Select("SELECT tc.*, mc.name as className, mt.teacher_name as teacherName " +
            "FROM m_teaching_calling tc " +
            "JOIN m_teaching_student_in_class tsic ON tc.class_id = tsic.class_id " +
            "JOIN m_manager_class mc ON tc.class_id = mc.id " +
            "JOIN m_manager_teacher mt ON tc.creator = mt.id " +
            "WHERE tsic.student_id = #{studentId} " +
            "AND tc.ended = '0' " +
            "AND tc.end_time > NOW()")
    List<Map<String, Object>> getPendingCallsByStudentId(Integer studentId);

    @Select("SELECT * FROM m_teaching_calling " +
            "WHERE class_id = #{classId} " +
            "AND ended = 0 " +  // 未结束
            "AND end_time > NOW() " +  // 结束时间大于当前时间
            "LIMIT 1")
    TeachingCalling getActiveCall(Integer classId);

    // 更新点名状态为已结束
    @Update("UPDATE m_teaching_calling " +
            "SET ended = 1 " +
            "WHERE end_time <= NOW() " +  // 结束时间小于等于当前时间
            "AND ended = 0")  // 之前未结束的
    void updateExpiredCalls();

    @Select("SELECT tsic.id as stuInClassId " +
            "FROM m_teaching_calling tc " +
            "JOIN m_teaching_student_in_class tsic ON tc.class_id = tsic.class_id " +
            "WHERE tc.id = #{callId} AND tsic.student_id = #{studentId}")
    Integer getStuInClassId(@Param("callId") Integer callId, @Param("studentId") Integer studentId);

}
